package com.mydemo.game.hireStage;

import com.mydemo.entity.Car;
import com.mydemo.entity.Save;
import com.mydemo.game.hireStage.random.CarRandom;
import com.mydemo.print.Print;
import com.mydemo.utils.dataUtils.DataUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import static java.lang.Thread.sleep;

public class UsedCarMarket {
    private static final List<Car> chosenCars = new ArrayList<>(); // 创建一个列表用于存储已选择的司机

    public static final Save usedCarMarket(Save save) {
        DataUtil<Car, ?> carDataUtil = new DataUtil<>(Car.class, "Car");
        List<Car> carList = carDataUtil.select().selectAll();
        for (int i = 0;i<3;i++){
            carList.add(CarRandom.generateRandomCar());
        }
        int i = 1;
        for (Car c :
                carList) {
            c.setId(i);
            i++;
        }
        boolean flag = true;
        while (flag) {
            System.out.println("可供选择的车辆");
            for (Car car :
                    carList) {
                Print.printCar(car);
            }
            System.out.println("--------------------");
            System.out.println("已选择的车辆");
            for (Car c :
                    chosenCars) {
                Print.printCar(c);
            }
            System.out.println("租赁请按序号，退出请按0");
            Scanner scanner = new Scanner(System.in);
            int choice = scanner.nextInt();
            if (choice == 0) {
                flag = false;
            } else {
                Car selectCar = getCarById(carList, choice);
                if (selectCar != null) {
                    if (LeaseCars.leaseCars(save, selectCar)) {
                        carList.remove(selectCar);
                        chosenCars.add(selectCar);
                        System.out.println("已选择车辆：" + selectCar.getCarBrand() + selectCar.getCarModel() + selectCar.getCarModelDetail());
                    } else {
                        System.out.println("放弃选择");
                    }
                } else {
                    System.out.println("未找到对应ID的车辆");
                    try {
                        sleep(1000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
        chosenCars.clear();
        return save;
    }

    private static Car getCarById(List<Car> cars, int id) {
        for (Car car :
                cars) {
            if (car.getId() == id) {
                return car;
            }
        }
        return null;
    }
}
